package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    @Override
    public IPage<HistoryItemVo> pageHistoryItemByUserId(Page<HistoryItemVo> historyItemVoPage, Long userId) {
        return browsingHistoryMapper.pageHistoryItemByUserId(historyItemVoPage, userId);
    }

    /**
     * 保存用户浏览记录
     * 当用户浏览某个房间时，调用此方法保存用户的浏览历史
     * 如果用户已经浏览过该房间，则更新最后浏览时间；否则，创建新的浏览记录
     *
     * @param userId 用户ID，用于标识用户
     * @param id 房间ID，用于标识用户浏览的房间
     */
    @Async
    @Override
    public void saveHistory(Long userId, Long id) {
        // 创建新的浏览历史对象
        BrowsingHistory browsingHistory = new BrowsingHistory();
        // 设置浏览历史的用户ID
        browsingHistory.setUserId(userId);
        // 设置浏览历史的房间ID
        browsingHistory.setRoomId(id);
        // 设置浏览时间为当前时间
        browsingHistory.setBrowseTime(new Date());

        // 构造查询条件，检查用户是否已经浏览过该房间
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<BrowsingHistory>()
                .eq(BrowsingHistory::getRoomId, id)
                .eq(BrowsingHistory::getUserId, userId);
        // 查询满足条件的浏览记录数量
        Long count = browsingHistoryMapper.selectCount(queryWrapper);
        if (count > 0) {
            // 如果用户已经浏览过该房间，构造更新条件
            LambdaUpdateWrapper<BrowsingHistory> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(BrowsingHistory::getUserId, userId)
                         .eq(BrowsingHistory::getRoomId, id);
            // 更新浏览记录
            browsingHistoryMapper.update(browsingHistory, updateWrapper);
        } else {
            // 如果用户尚未浏览过该房间，保存新的浏览记录
            this.save(browsingHistory);
        }
    }
}




